<?php

include_once 'XmlSpreadsheetWorksheet.php';

/**
 * XmlSpreadsheet
 *
 * @package XmlSpreadsheet
 * @author Aleksey Voronoy <aleksey.voronoy@gmail.com>
 */
class XmlSpreadsheet {

	private $headers;
	private $tmplWorkbook;
	private $properties = array();
	private $worksheets = array();
	private $activeWorksheet;

	function  __construct() {
		$this->headers = '<?xml version="1.0"?>'
				. "\n"
				. '<?mso-application progid="Excel.Sheet"?>'
				. "\n"
			;
		$this->tmplWorkbook = '<Workbook'
				. ' xmlns="urn:schemas-microsoft-com:office:spreadsheet"'
				. ' xmlns:o="urn:schemas-microsoft-com:office:office"'
				. ' xmlns:x="urn:schemas-microsoft-com:office:excel"'
				. ' xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"'
				. ' xmlns:html="http://www.w3.org/TR/REC-html40">'
				. '%s'
				. '</Workbook>'
			;
	}

	public function render() {
		return $this->headers
				. sprintf($this->tmplWorkbook, $this->getProperties() . $this->getStyles() . $this->renderWorksheets());
	}

	public function createWorksheet($name = '') {
		$worksheet = new XmlSpreadsheetWorksheet($name);
		$this->addWorksheet($worksheet);
		return $worksheet;
	}

	public function addWorksheet(XmlSpreadsheetWorksheet $worksheet) {
		return array_push($this->worksheets, $worksheet);
	}

	public function setActiveWorksheet($index = 0) {
		if ($index > count($this->worksheets) - 1) {
			trigger_error('Worksheet doesn\'t exists');
		} else {
			$this->activeWorksheet = $index;
		}
	}

	public function getActiveSheet() {
		return $this->worksheets[$this->activeWorksheet];
	}

	public function setProperty($property, $value) {
		$properties = array(
			'Author',
			'LastAuthor',
			'Created',
			'Company',
			'Version',
		);
		if (!in_array($property, $properties)) {
			return false;
		} else {
			$this->properties[$property] = htmlentities($value, ENT_QUOTES, 'UTF-8');
			return true;
		}
	}
	
	private function getProperties() {
		if (empty($this->properties)) return '';
		$properties = '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">';
		foreach ($this->properties as $property => $value) {
			$properties .= '<' . $property . '>' . $value . '</' . $property . '>';
		}
		$properties .= '</DocumentProperties>';
		return $properties;
	}

	private function getStyles() {
		if (empty($this->worksheets)) {
			return '';
		}
		$styles = '<Styles>';
		foreach ($this->worksheets as $worksheet) {
			$styles .= $worksheet->getStyles();
		}
		$styles .= '</Styles>';
		return $styles;
	}
	
	private function renderWorksheets() {
		if (empty($this->worksheets)) {
			return '';
		}
		$worksheets = '';
		foreach ($this->worksheets as $worksheet) {
			$worksheets .= $worksheet->render();
		}
		return $worksheets;
	}


}


?>